import spanIcon from '@/assets/span.png';
import { conversationDelete, conversationList } from '@/services/chat';
import { DeleteOutlined } from '@ant-design/icons';
import { Button, Input, Modal, Pagination, Select, Table, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

const { Option } = Select;

interface HistoryItem {
  id: string;
  content: string;
  createTime: string;
  project: string;
  requirement: string;
}

interface HistoryModalProps {
  visible: boolean;
  projectList: any[];
  dropDownList: any[];
  onCancel: () => void;
  onConfirm: () => void;
  onDelCallBack: () => void;
}

const HistoryModal: React.FC<HistoryModalProps> = ({
  visible,
  projectList,
  dropDownList,
  onCancel,
  onConfirm,
  onDelCallBack,
}) => {
  const [data, setData] = useState<HistoryItem[]>([]);
  const [filteredData, setFilteredData] = useState<HistoryItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedProject, setSelectedProject] = useState<string>('');
  const [selectedRequirement, setSelectedRequirement] = useState<string>('');
  const [searchText, setSearchText] = useState<string>('');

  const fetchData = async () => {
    try {
      const { code, data } = await conversationList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        projectId: selectedProject,
        requirementId: selectedRequirement,
        description: searchText,
      });
      if (code === 200) {
        setData(data.list);
        setFilteredData(data.list);
        setPagination((prev) => ({ ...prev, total: data.total }));
      }
    } catch (error) {
      console.error('Failed to fetch conversation list:', error);
      message.error('获取对话记录失败');
    }
  };

  useEffect(() => {
    if (visible) {
      fetchData();
    }
  }, [
    visible,
    pagination.current,
    pagination.pageSize,
    selectedProject,
    selectedRequirement,
    searchText,
  ]);

  const handleDelete = async (id: string) => {
    try {
      const { code } = await conversationDelete(id);
      if (code === 200) {
        message.success('删除成功');
        onDelCallBack();
        fetchData();
      }
    } catch (error) {
      console.error('Failed to delete conversation:', error);
      message.error('删除失败');
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleProjectChange = (value: string) => {
    setSelectedProject(value);
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleRequirementChange = (value: string) => {
    setSelectedRequirement(value);
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
  };

  const columns = [
    {
      title: '',
      dataIndex: 'description',
      key: 'description',
      render: (text: string) => (
        <div className={styles.contentCell}>
          <span className={styles.iconWrapper}>
            <img src={spanIcon} alt="Chat" className={styles.chatIcon} />
          </span>
          {text}
        </div>
      ),
    },
    {
      title: '',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (text: string) => (
        <span className={styles.dateText}>
          {moment(text).format('YYYY-MM-DD HH:mm:ss')}
        </span>
      ),
    },
    {
      title: '',
      key: 'action',
      render: (_: any, record: HistoryItem) => (
        <DeleteOutlined
          className={styles.deleteIcon}
          onClick={() => handleDelete(record.id)}
        />
      ),
    },
  ];

  return (
    <Modal
      title="历史对话记录"
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="confirm" type="primary" onClick={onConfirm}>
          确认
        </Button>,
      ]}
      width={1000}
      className={styles.historyModal}
    >
      <div className={styles.filterRow}>
        <div className={styles.leftSearch}>
          <Select
            options={projectList}
            allowClear
            placeholder="请选择"
            fieldNames={{ label: 'name', value: 'id' }}
            style={{ width: 200, marginRight: 16 }}
            onChange={handleProjectChange}
          />

          <Select
            options={dropDownList}
            placeholder="请选择"
            allowClear
            style={{ width: 200 }}
            fieldNames={{ label: 'title', value: 'id' }}
            onChange={handleRequirementChange}
          />
        </div>

        <Input.Search
          placeholder="模糊搜索"
          style={{ width: 450 }}
          onSearch={handleSearch}
        />
      </div>
      <div className={styles.tableBox}>
        <Table
          columns={columns}
          dataSource={filteredData}
          pagination={false}
          rowSelection={{
            type: 'checkbox',
          }}
          onChange={handleTableChange}
        />
      </div>

      <div className={styles.paginationWrapper}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={(page, pageSize) =>
            setPagination({ current: page, pageSize, total: pagination.total })
          }
        />
      </div>
    </Modal>
  );
};

export default HistoryModal;
